package com.asistencia.security;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.stereotype.Component;

import com.asistencia.businness.ProfessorBusiness;
import com.asistencia.businness.StudentBusiness;
import com.asistencia.domain.Professor;
import com.asistencia.domain.Student;
import com.asistencia.util.Constant;

@SuppressWarnings("deprecation")
@Component("authenticationProvider")
public class AuthenticationProviderImpl implements AuthenticationProvider {

	@Autowired
	private UserSecutiry userSecutiry;
	@Autowired
	private StudentBusiness studentBusiness;
	@Autowired
	private ProfessorBusiness professorBusiness;
	
	
	@Override
	public Authentication authenticate(Authentication authentication)
			throws AuthenticationException {
		System.out.println("Username:" +authentication.getName());
		
		try {
			String username = authentication.getName();
			String password = authentication.getCredentials().toString();
			if(isNumeric(username)){
				Student student = studentBusiness.loginStudent(username, password);
				if(student != null){
					userSecutiry.setIdUser(student.getIdStudent());
					userSecutiry.setUsername(username);
					List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
					authorities.add(new GrantedAuthorityImpl(Constant.STUDENT_ROLE));
					return new UsernamePasswordAuthenticationToken(userSecutiry, authentication.getCredentials(), authorities);
				}else{
					return null;
				}
			}else{
				Professor professor = professorBusiness.loginProfessor(username, password);
				if(professor != null){
					userSecutiry.setIdUser(professor.getIdProfessor());
					userSecutiry.setUsername(username);
					List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
					authorities.add(new GrantedAuthorityImpl(Constant.PROFESSOR_ROLE));
					return new UsernamePasswordAuthenticationToken(userSecutiry, authentication.getCredentials(), authorities);
				}else{
					return null;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	@Override
	public boolean supports(Class<?> authentication) {
		return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));
	}
	
	public boolean isNumeric(String secuence){
		try {
			Integer.parseInt(secuence);
			return true;
		} catch (Exception e) {
			return false;
		}
	}

}
